package net.keebook.webapp.ws;

import javax.ejb.Stateless;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.ws.rs.Consumes;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import net.keebook.webapp.entity.KeeBook;
import net.keebook.webapp.entity.User;
import net.keebook.webapp.model.SessionModel;
import net.keebook.webapp.util.AccessRight;

import org.apache.log4j.Logger;
import org.json.JSONException;
import org.json.JSONObject;


@Path("/{username}/updatekeebook")
@Stateless
public class UpdateKeeBookService extends WebService {
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	@Produces(MediaType.APPLICATION_JSON)
	public String saveSettings(@Context HttpServletRequest request, @PathParam("username") String username, String jsonString) {
		Logger.getLogger(this.getClass()).info("Incoming request");
		Logger.getLogger(this.getClass()).trace("Request string: " + jsonString);
		
		JSONObject input = getInput(jsonString);
		JSONObject result = new JSONObject();
		try {
			String auth = input.has("auth") ? input.getString("auth") : AUTH_PASSWORD;
			String password = input.getString("password");
			String keeBookId = input.getString("keeBook");
			String keeBookChecksum = input.getString("keeBookChecksum");
			
			HttpSession httpSession = request.getSession(true);
			SessionModel sessionModel = SessionModel.getInstance(httpSession);
			
			// Authentication
			User user = authenticate(username, password, auth, sessionModel);
			if (user == null) {
				Logger.getLogger(this.getClass()).warn("Authentication failed for user " + username);
				result.put("authSuccess", false);
				result.put("success", false);
				return getResponse(result);
			}
			username = user.getUsername();
			
			// Open Key Box
			KeeBook keeBook = getKeeBook(keeBookId, keeBookChecksum);
			if (keeBook == null || !getKeeBookDao().canAccess(user.getId(), keeBook.getId(), AccessRight.OWNER)) {
				Logger.getLogger(this.getClass()).warn("Kee Book authentication failed for user " + username + " and kee book " + keeBookId);
				result.put("authSuccess", false);
				result.put("success", false);
				return getResponse(result);
			}
			
			Logger.getLogger(this.getClass()).info("User " + username + " authenticated successfully (user id: "+user.getExposableId()+" / kee book id: "+keeBook.getExposableId()+")");
			result.put("authSuccess", true);
			
			if (!input.has("data")) {
				Logger.getLogger(this.getClass()).warn("Data element missing in request");
				result.put("success", false);
				return getResponse(result);
			}
			JSONObject data = input.getJSONObject("data");
			if (data.has("title")) keeBook.setName(data.getString("title"));
			if (data.has("keeBookChecksum")) keeBook.setKeyphraseChecksum(data.getString("keeBookChecksum"));
			getKeeBookDao().update(keeBook);
			
			result.put("success", true);
			result.put("keeBookId", keeBook.getExposableId());
		} catch (JSONException e) {
			e.printStackTrace();
			return getResponse("{'success': false, 'authSuccess': false}");
		}
		
		return getResponse(result);
	}
}
